import InboundPlanApi from '../../../common/api/breed/inboundplan.api.js';

let _vm;
(function (window, document, $) {
    $(function () {
        let id = getUrlKey('id');
        let destFarmName = Utils.GetSessionStorage('destFarmName');
        let signLocation = '';
        let isClickable = false; // 初始状态为不可点击
        let subdataWarList = [];
        let configState = false;

        let sid = Utils.GetSessionStorage('Sid');
        let url = encodeURIComponent(window.location.href.split('#')[0]);
        // let sid = 'gh_94f4b4e471ab';
        // let url = encodeURIComponent('https://qas.it.ynsnjt.net/h5it/html/features/breed/inboundplan/inboundplansign.html');

        InboundPlanApi.getjssdksign(sid, url).then((res) => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.appid, // 必填，公众号的唯一标识
                timestamp: res.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.nonceStr, // 必填，生成签名的随机串
                signature: res.signature, // 必填，签名
                jsApiList: ['scanQRCode'], // 必填，需要使用的JS接口列表
            });

            wx.error(function (res) {
                alert(`微信JS-SDK配置失败：${res.errMsg}`);
                return;
            });

            wx.ready(function () {
                wx.checkJsApi({
                    jsApiList: ['scanQRCode'], // 检测扫码功能
                    success: function (res) {
                        if (res.checkResult.scanQRCode) {
                            configState = true;
                            console.log('当前微信支持扫码功能');
                        } else {
                            console.log('当前微信版本不支持扫码功能');
                        }
                    },
                    fail: function (err) {
                        alert(`检测失败：${err}`);
                    },
                });
            });
        });

        // 扫一扫
        $('#btnScan').click(function () {
            if (configState == true) {
                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果
                    scanType: ['qrCode'], // 可以指定只扫二维码
                    success: function (res) {
                        var result = res.resultStr; // 扫码返回的结果
                        console.log('扫描结果: ' + result);
                        let newList = subdataWarList.find((s) => s.name == result)?.farm || [];
                        if (newList.some((s) => s.includes(destFarmName))) {
                            if (!Utils.IsNotNull(id)) {
                                return $.toptip(`单据id为空!`, 'warning');
                            }
                            if (!Utils.IsNotNull(signLocation)) {
                                return $.toptip(`签到隔离点为空!`, 'warning');
                            }
                            let pSCode = $('#pSCode').val();
                            let mSCode = $('#mSCode').val();
                            if (!Utils.IsNotNull(pSCode)) {
                                return $.toptip(`人员采样编码不能为空!`, 'warning');
                            }
                            // if (!Utils.IsNotNull(mSCode)) {
                            //     return $.toptip(`物资采样编码不能为空!`, 'warning');
                            // }
                            InboundPlanApi.checkinEntryplans({ id: id, location: result, pSCode: pSCode, mSCode: mSCode }).then((res) => {
                                $('#signSuccess').css('display', 'block');
                                $('#signBefore').css('display', 'none');
                                $('#btnScan').css('display', 'none');
                                $('#locationStr').text(result);
                                $('#timeStr').text(moment(new Date()).format('HH:mm'));
                            });
                        } else {
                            $.toptip('目的地不在隔离点内', 'error');
                            return;
                        }
                    },
                    fail: function (err) {
                        alert('扫描失败: ' + JSON.stringify(err));
                    },
                });
            } else {
                alert(`微信JS-SDK配置检测失败`);
            }
        });

        // 初始化地图
        var map,
            placeSearch,
            geolocation,
            marker,
            mapMarkers = [],
            mapCircles = [];
        initMap();
        getSystemParam();

        // 搜索按钮点击事件
        $('#search-btn').click(handleSearch);

        // 输入框回车事件
        $('#search-input').keypress(function (e) {
            if (e.which === 13) {
                handleSearch();
            }
        });

        // 定位按钮事件
        $('.amap-geolocation-con').click(getCurrentLocation);

        // 放大按钮事件
        $('#zoom-in').click(function () {
            map.setZoom(map.getZoom() + 1);
        });

        // 缩小按钮事件
        $('#zoom-out').click(function () {
            map.setZoom(map.getZoom() - 1);
        });

        // 初始化时间显示
        updateTime();
        setInterval(updateTime, 1000);

        // 返回按钮点击事件
        $('#submitItemTab').click(function () {
            location.href = `./inboundplanlist.html`;
        });

        // 签到按钮点击事件
        $('#checkin-btn').on('click', function () {
            if (isClickable == true) {
                if (!Utils.IsNotNull(id)) {
                    return $.toptip(`单据id为空!`, 'warning');
                }
                if (!Utils.IsNotNull(signLocation)) {
                    return $.toptip(`签到隔离点为空!`, 'warning');
                }
                let pSCode = $('#pSCode').val();
                let mSCode = $('#mSCode').val();
                if (!Utils.IsNotNull(pSCode)) {
                    return $.toptip(`人员采样编码不能为空!`, 'warning');
                }
                // if (!Utils.IsNotNull(mSCode)) {
                //     return $.toptip(`物资采样编码不能为空!`, 'warning');
                // }

                // 显示加载中
                var $btn = $('#checkin-btn');
                $btn.addClass('weui-btn_loading');
                $btn.html('<i class="weui-loading"></i> 签到中');
                InboundPlanApi.checkinEntryplans({ id: id, location: signLocation, pSCode: pSCode, mSCode: mSCode }).then((res) => {
                    $('#signSuccess').css('display', 'block');
                    $('#signBefore').css('display', 'none');
                    $('#btnScan').css('display', 'none');
                    $('#locationStr').text(signLocation);
                    $('#timeStr').text(moment(new Date()).format('HH:mm'));
                });
            } else {
                console.log('不可点击');
                return false;
            }
        });

        // 初始化地图
        function initMap() {
            // 安全配置（高德新版要求）
            window._AMapSecurityConfig = {
                securityJsCode: '657d628d60d09241b068d846b9113dae',
            };

            // 创建地图
            map = new AMap.Map('map-container', {
                center: [102.722344, 25.036881],
                zoom: 15,
                viewMode: '2D',
            });

            // 添加缩放控件
            map.addControl(
                new AMap.ToolBar({
                    position: 'RB', // 右上角
                }),
            );

            // 初始化地点搜索
            placeSearch = new AMap.PlaceSearch({
                pageSize: 10,
                pageIndex: 1,
                city: '北京',
                map: map,
            });

            // 初始化地理定位
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 10000,
                showMarker: true,
                buttonPosition: 'RB',
                buttonOffset: new AMap.Pixel(14, 150),
                showMarker: false,
            });
            map.addControl(geolocation);

            // 默认定位到当前城市
            getCurrentLocation();
        }

        // 搜索处理函数
        function handleSearch() {
            var keyword = $('#search-input').val().trim();
            if (keyword.length > 0) {
                placeSearch.search(keyword, function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        displaySearchResults(result.poiList.pois);
                    } else {
                        $('#search-results').html('<div class="result-item">未找到结果</div>').show();
                    }
                });
            }
        }

        // 显示搜索结果
        function displaySearchResults(pois) {
            var html = '';
            pois.forEach(function (poi) {
                html += `
                <div class="result-item" data-lng="${poi.location.lng}" data-lat="${poi.location.lat}">
                    <div class="result-name">${poi.name}</div>
                    <div class="result-address">${poi.address}</div>
                </div>
                `;
            });

            $('#search-results').html(html).show();

            // 点击搜索结果定位到该位置
            $('.result-item').click(function () {
                var lng = $(this).data('lng');
                var lat = $(this).data('lat');
                map.setCenter([lng, lat]);
                addMarker(new AMap.LngLat(lng, lat));
                $('#search-results').hide();
                $('#search-input').blur();
            });
        }

        // 添加标记
        function addMarker(lnglat) {
            // 清除旧标记
            if (marker) {
                marker.setMap(null);
            }

            // 添加新标记
            marker = new AMap.Marker({
                position: lnglat,
                map: map,
                title: '我的位置',
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
            });

            // // 获取详细地址
            // getAddress(lnglat.getLng(), lnglat.getLat(), function(address) {
            //     marker.setLabel({
            //         content: address,
            //         offset: new AMap.Pixel(20, 20)
            //     });
            // });
        }

        // 获取地址信息
        function getAddress(lng, lat, callback) {
            AMap.plugin('AMap.Geocoder', function () {
                var geocoder = new AMap.Geocoder();
                geocoder.getAddress([lng, lat], function (status, result) {
                    if (status === 'complete' && result.info === 'OK') {
                        callback(result.regeocode.formattedAddress);
                    } else {
                        callback('未知位置');
                    }
                });
            });
        }

        // 使用高德地图定位 获取当前位置
        function getCurrentLocation() {
            geolocation.getCurrentPosition(function (status, result) {
                if (status == 'complete') {
                    var currentLng = result.position.lng;
                    var currentLat = result.position.lat;

                    map.setCenter([result.position.lng, result.position.lat]);
                    addMarker(new AMap.LngLat(result.position.lng, result.position.lat));

                    // 检查每个打卡点
                    var nearestDistance = Infinity;
                    var nearestCheckpoint = null;
                    let newList = [];
                    subdataWarList.forEach(function (checkpoint) {
                        var targetLng = parseFloat(checkpoint.lon);
                        var targetLat = parseFloat(checkpoint.lat);
                        var radius = 500;

                        if (isNaN(targetLng) || isNaN(targetLat) || isNaN(radius)) {
                            $.toptip(`${checkpoint.name}无效的坐标或半径`, 'error');
                            return;
                        }

                        // 计算距离
                        var distance = AMap.GeometryUtil.distance([targetLng, targetLat], [currentLng, currentLat]);

                        // 更新最近打卡点信息
                        if (distance < nearestDistance) {
                            nearestDistance = distance;
                            nearestCheckpoint = checkpoint;
                        }

                        // 判断是否在范围内
                        if (distance <= radius) {
                            newList.push(checkpoint.name);
                        }
                    });

                    if (newList.length > 0) {
                        signLocation = newList[0];
                        $('#checkin-str').text('签到');
                        isClickable = true;
                    } else {
                        signLocation = '';
                        $('#checkin-str').text('不在范围内');
                        isClickable = false;
                    }

                    // 调整地图视图
                    var allMarkers = mapMarkers.concat([marker]);
                    map.setFitView(allMarkers);
                } else {
                    // 默认昆明恒隆位置
                    map.setCenter([102.722344, 25.036881]);
                    $.toptip('定位失败', 'error');
                }
            });
        }

        // 更新当前时间显示
        function updateTime() {
            var now = new Date();
            var hours = now.getHours().toString().padStart(2, '0');
            var minutes = now.getMinutes().toString().padStart(2, '0');
            $('#current-time').text(hours + ':' + minutes);
        }

        function getSystemParam() {
            // 获取系统参数：牧场组织
            InboundPlanApi.getPrmtSettings('LIVESTOCK-ISOLATION').then((result) => {
                subdataWarList = JSON.parse(result);
                updateMapMarkers();
            });
        }

        // 更新地图标记
        function updateMapMarkers() {
            // 清除之前的标记
            clearMapMarkers();

            // 添加新的标记
            subdataWarList.forEach(function (checkpoint) {
                var targetLng = parseFloat(checkpoint.lon);
                var targetLat = parseFloat(checkpoint.lat);
                var radius = 500;

                if (!isNaN(targetLng) && !isNaN(targetLat) && !isNaN(radius)) {
                    // 添加打卡点标记
                    var marker = new AMap.Marker({
                        position: [targetLng, targetLat],
                        map: map,
                        title: checkpoint.name,
                    });
                    mapMarkers.push(marker);

                    // 添加打卡范围圆
                    var circle = new AMap.Circle({
                        center: [targetLng, targetLat],
                        radius: radius,
                        strokeColor: '#FF33FF',
                        strokeOpacity: 1,
                        strokeWeight: 2,
                        fillColor: '#1791fc',
                        fillOpacity: 0.4,
                        map: map,
                    });
                    mapCircles.push(circle);
                }
            });
        }

        // 清除地图标记
        function clearMapMarkers() {
            mapMarkers.forEach(function (marker) {
                map.remove(marker);
            });
            mapCircles.forEach(function (circle) {
                map.remove(circle);
            });
            mapMarkers = [];
            mapCircles = [];
        }

        // 获取地址栏的 参数
        function getUrlKey(name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }
    });
})(window, document, jQuery);
